package com.lt.lumentracks.service.Impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.lumentracks.context.BaseContext;
import com.lt.lumentracks.entity.po.ChatMessage;
import com.lt.lumentracks.entity.vo.common.PageVO;
import com.lt.lumentracks.entity.vo.common.Result;
import com.lt.lumentracks.mapper.ChatMessageMapper;
import com.lt.lumentracks.service.IChatMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 聊天消息表 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-10-06
 */
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    // 根据会话id分页查询
    @Override
    public PageVO<ChatMessage> getByPage(Long conversationId, long pageNum, long pageSize) {
        Page<ChatMessage> page = this.lambdaQuery()
                .eq(ChatMessage::getConversationId, conversationId)
                .eq(ChatMessage::getStatus, 1) // 正常状态的
                .orderByDesc(ChatMessage::getCreateTime)
                .page(Page.of(pageNum, pageSize));

        return PageVO.of(page);
    }

    // 撤回消息
    @Override
    public Result<String> revokeMsg(Long id) {
        Integer userId = BaseContext.getCurrentId();
        ChatMessage msg = this.getById(id);
        if (msg == null) {
            return Result.error("消息不存在");
        }
        if (!msg.getSenderId().equals(userId)) {
            return Result.error("您没有权限撤回该条消息");
        }
        if (msg.getRevoked()) {
            return Result.error("该消息已是撤回状态");
        }
        msg.setRevoked(true);
        this.updateById(msg); // 更新
        return Result.success();
    }

    // 批量查询每个会话的最后一条消息
    @Override
    public List<ChatMessage> queryLastMessageByConversationIds(List<Long> conversationIds) {
        if (CollectionUtils.isEmpty(conversationIds)) {
            return Collections.emptyList();
        }
        return chatMessageMapper.selectLastMessagesByConversationIds(conversationIds);
    }
}
